package com.yousu.wxqropendoor.controller.wxapi;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yousu.wxqropendoor.entity.ManageHouse;
import com.yousu.wxqropendoor.entity.WxUserHouselist;
import com.yousu.wxqropendoor.service.IManageHouseService;
import com.yousu.wxqropendoor.service.IWxUserHouselistService;
import com.yousu.wxqropendoor.utils.AppResult;
import com.yousu.wxqropendoor.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author ：chenwenbin
 * @date ：Created in 2020/02/27 16:36
 * @description ：微信API , 接口路径前缀/wxapi
 */
@RestController
@Slf4j
@RequestMapping("api/wxapi")
public class WxApiController {
    @Autowired
    IManageHouseService manageHouseService;
    @Autowired
    IWxUserHouselistService wxUserHouselistService;


    @Value("${wxpay.AppID}")
    private String AppID;
    @Value("${wxpay.Secret}")
    private String Secret;

    /**
     * 微信小程序，获取用户openid
     *
     * @param code 用户code
     * @return openid
     */
    @RequestMapping(value = "getOpenid")
    public Object getOpenid(@RequestParam(value = "code") String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppID + "&secret=" + Secret + "&js_code=" + code + "&grant_type=authorization_code";
        String sendMsgByGet = null;
        // 发起get
        sendMsgByGet = HttpClientUtil.doGet(url);
        Object parse = JSON.parse(sendMsgByGet);
        return sendMsgByGet;
    }

    /**
     * 注册用户openid及基本信息
     *
     * @param communityId 小区id
     * @param buildingId  楼栋id
     * @param ownerName   户主姓名
     * @param ownerPhone  户主电话
     * @param openid      微信openid(非空)
     * @return
     */
    @PostMapping("/regManageHouseAndOpenid")
    public Object regManageHouseAndOpenid(
            @RequestParam(value = "community_id") Integer communityId,
            @RequestParam(value = "building_id") Integer buildingId,
            @RequestParam(value = "owner_name") String ownerName,
            @RequestParam(value = "owner_phone") String ownerPhone,
            @RequestParam(value = "openid") String openid
    ) {
        // 1.从manage_house表查询用户
        QueryWrapper<ManageHouse> query = new QueryWrapper<>();
        query.eq("community_id", communityId);
        query.eq("building_id", buildingId);
        query.eq("owner_name", ownerName);
        query.eq("owner_phone", ownerPhone);
        List<ManageHouse> list = manageHouseService.list(query);
        if (list.size() == 0) {
            return AppResult.error("用户信息不匹配，没有找到此用户");
        }
        List<Map> ouputMap = new ArrayList<>();
        // 3.查询是否注册过，没注册则更新到wx_user_houselist表
        for (ManageHouse manageHouse : list) {
            // 查询
            QueryWrapper<WxUserHouselist> queryWxUserHouselist = new QueryWrapper<>();
            queryWxUserHouselist.eq("house_id", manageHouse.getId());
            queryWxUserHouselist.eq("user_openid", openid);
            int count = wxUserHouselistService.count(queryWxUserHouselist);
            Map<String, Object> msgMap = new HashMap<>();
            if (count > 0) {
                msgMap.put("msg", "此用户已经与" + manageHouse.getBuildingName() + "-" + manageHouse.getHouseNo() + "绑定，请勿重复绑定");
            } else {
                // 新增
                WxUserHouselist wxUserHouselist = new WxUserHouselist();
                wxUserHouselist.setHouseId(manageHouse.getId());
                wxUserHouselist.setUserOpenid(openid);
                wxUserHouselist.setStatus(0);
                wxUserHouselist.setGmtCreate(LocalDateTime.now());
                wxUserHouselist.setIsPre(0);
                wxUserHouselistService.save(wxUserHouselist);
                msgMap.put("msg", "用户与" + manageHouse.getBuildingName() + "-" + manageHouse.getHouseNo() + "绑定成功！");
            }
            ouputMap.add(msgMap);
        }
        return AppResult.ok(ouputMap);
    }

    /**
     * 检查住户列表是否存在有此openid,有则返回当前数据
     *
     * @param openId 用户openid
     * @return AppResult
     */
    @PostMapping("/checkManageHouseList")
    public AppResult checkManageHouseList(@RequestParam(value = "openId") String openId) {
        try {
            QueryWrapper<WxUserHouselist> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_openid", openId).eq("status", 0);
            List<WxUserHouselist> wxUserHouselists = wxUserHouselistService.list(queryWrapper);
            if (wxUserHouselists.size() == 0) {
                return AppResult.error("没有检索到此openid");
            }
            // 循环找出默认房户号，并输出
            for (WxUserHouselist wxUserHouselist : wxUserHouselists) {
                Integer isPre = wxUserHouselist.getIsPre();
                if (isPre == 0) {
                    Integer houseId = wxUserHouselist.getHouseId();
                    ManageHouse manageHouse = manageHouseService.getById(houseId);
                    return AppResult.ok(manageHouse);
                }
            }
            // 没有默认房户号，提示前端
            Integer houseId = wxUserHouselists.get(0).getHouseId();
            ManageHouse manageHouse = manageHouseService.getById(houseId);
            return AppResult.build(200, "检索到openid，但是没有设置默认房户号,请提示用户设置", manageHouse);
        } catch (Exception e) {
            log.error("检索用户openid出错", e);
            return AppResult.error("服务器出错");
        }
    }
}
